// GuideManager.ts
import { _decorator, Component, director, resources, JsonAsset, instantiate, find, Node, Prefab, UITransform, tween, Vec3, Tween, Label, UIOpacity, Color, Sprite } from 'cc';
import { GuideEvent } from './GuideEvent';
const { ccclass } = _decorator;

@ccclass('GuideManager')
export class GuideManager extends Component {
    private currentStep: number = 0;
    private steps: any[] = [];

    private fingerNode: Node = null!;
    private LabelNode: Node = null!;
    private targetNode: Node = null!;

    onLoad() {
        this.initGuideRoot();
        this.loadConfig();
    }

    private initGuideRoot() {
        const guideRoot = new Node('GuideRoot');
        guideRoot.addComponent(UITransform);
        this.node.parent.addChild(guideRoot);
        guideRoot.getComponent(UITransform).setAnchorPoint(0.5, 0.5)
        // this.node = guideRoot;
        // 加载并实例化遮罩和对话框
        resources.load('guide/prefabs/GuideMask', (err, prefab) => {
            const maskNode = instantiate(prefab as Prefab);
            guideRoot.addChild(maskNode);
        });

        resources.load('guide/prefabs/GuideDialog', (err, prefab) => {
            const dialogNode = instantiate(prefab as Prefab);
            this.fingerNode = dialogNode.getChildByName('sprite');
            this.LabelNode = dialogNode.getChildByName('Label')
            guideRoot.addChild(dialogNode);
        });
    }

    private loadConfig() {
        resources.load('guide/GuideStepConfig', JsonAsset, (err, asset) => {
            if (err) {
                console.error('引导配置加载失败:', err);
                return;
            }
            this.steps = asset!.json.steps;
        });
    }

    public startGuide() {
        console.log('开始引导')
        this.currentStep = 0;
        this.executeStep(this.steps[0]);
    }

    private executeStep(step: any) {
        // 派发步骤开始事件
        director.emit(GuideEvent.STEP_START, step);
        const targetNode = find(step.targetNode);
        this.targetNode = targetNode
        if (step.mask) {
            if (targetNode) {
                director.emit(GuideEvent.SHOW_MASK, targetNode, step.highlight);
                director.emit(GuideEvent.SHOW_DIALOG, targetNode, step);
            }
        }

        if (step.fingerAni) {
            if (step.fingerAni === 'clickAni') {
                this.clickTween()
            } else if (step.fingerAni === 'slideTween') {
                this.slideTween(targetNode)
            } else if (step.fingerAni === 'lastTween') {
                this.scheduleOnce(() => {
                    this.lastStepGuide();
                }, 0.5)

            }
        }

        this.registerTrigger(step);
    }

    private registerTrigger(step: any) {
        switch (step.trigger) {
            case 'node_click':
                const node = find(step.targetNode);
                if (node) {
                    node.once(Node.EventType.TOUCH_END, this.onTrigger, this);
                }
                break;
            case 'onDoubleClick':
                director.once('onDoubleClick', this.onTrigger, this);
                break;
            case 'lastMove':
                director.once(step.eventName, this.onTrigger, this);
                break;
        }
    }

    private onTrigger(data?: any) {
        director.emit(GuideEvent.STEP_END);
        this.currentStep++;
        if (this.currentStep < this.steps.length) {
            this.executeStep(this.steps[this.currentStep]);
        } else {
            this.finishGuide();
        }
    }

    private finishGuide() {
        console.log('引导完成');
    }

    private currentTween = null;

    //点击
    private clickTween() {
        Tween.stopAll();
        // this.node.stopAllActions();
        if (this.currentTween) {
            this.currentTween.stop()
        }
        this.currentTween = tween(this.fingerNode)
            .to(0.2, { scale: new Vec3(1.2, 1.2, 1) }, { easing: 'sineInOut' }) // 放大到1.2倍
            .to(0.2, { scale: new Vec3(0.8, 0.8, 1) }, { easing: 'sineInOut' }) // 缩小到1倍
            .union()
            .repeatForever() // 设置动画循环播放 3 次
            // .repeat(3)
            .start();

        // ain.repeatForever()
    }

    private slideTween(targetNode: Node) {
        let localBoundingBox = targetNode.getComponent(UITransform).getBoundingBox();
        let worldPos = targetNode.getWorldPosition();
        Tween.stopAll();
        this.currentTween = tween(this.fingerNode)
        tween(this.fingerNode)
            .set({ worldPosition: new Vec3(worldPos.x - localBoundingBox.width * 0.4, worldPos.y - 100, 1) }) // 放大到1.2倍
            .to(1, { worldPosition: new Vec3(worldPos.x + localBoundingBox.width * 0.4, worldPos.y - 100, 1) }, { easing: 'sineInOut' }) // 缩小到1倍
            .union()
            .repeatForever() // 设置动画循环播放 3 次
            // .repeat(3)
            .start();

        // ain.repeatForever()
    }

    private cloneNode = null
    //最后一部引导
    private lastStepGuide() {

        if (this.cloneNode) {
            this.cloneNode.destroy()
            return
        }
        console.log("最后一步引导")
        //第一块拼图的正确位置
        const pi = { x: -320, y: -225, angle: [0, 360], reverse: 1 }//橙黄
        const piNode = instantiate(this.targetNode)
        piNode.angle = pi.angle[1]
        piNode.setParent(this.targetNode.parent)
        piNode.setPosition(pi.x, pi.y)
        piNode.addComponent(UIOpacity)
        this.cloneNode = piNode
        this.colorTween();

        // tween(piNode)
        // .to(0.5, { Opacity: 0 }, { easing: 'sineInOut' })   // 渐隐
        // .to(0.5, { opacity: 255 }, { easing: 'sineInOut' }) // 渐现
        // .union().
        // repeatForever().
        // start();

    }

    colorTween() {
        let c0 = new Color();  // 当前颜色
        let c1 = new Color(255, 0, 0);  // 初始颜色（红色）
        let c2 = new Color(0, 0, 255);  // 目标颜色（蓝色）
        // 设置当前颜色为 c1
        let color = this.cloneNode.getComponent(Sprite).Color as Color
        console.log('颜色',color)
        let color2 = new Color(color.r,color.g,color.b,0)
        // 使用tween库进行颜色渐变动画
        tween(color)
            .to(0.5, { r: color.r, g: color.g, b: color.b ,a:0}, {  // 目标颜色为蓝色
                onUpdate: () => {
                    // 每一帧更新时，将当前颜色赋值给精灵
                    this.cloneNode.getComponent(Sprite).Color = color2
                }
            })
            .to(0.5, { r: color.r, g: color.g, b: color.b ,a:255 }, {  // 目标颜色为红色
                onUpdate: () => {
                    // 每一帧更新时，将当前颜色赋值给精灵
                    this.cloneNode.getComponent(Sprite).Color = color
                }
            })
            .union()
            .repeatForever()  // 无限循环
            .start();  // 启动动画
    }


}